package org.demo.blog.controller;

import org.demo.base.auth.domain.SysUser;
import org.demo.base.auth.permission.NeedPermission;
import org.demo.base.file.domain.SysFile;
import org.demo.base.file.service.FileService;
import org.demo.base.mvc.HttpResult;
import org.demo.base.mvc.PageQuery;
import org.demo.base.mvc.PageResult;
import org.demo.base.util.LoginHelper;
import org.demo.blog.domain.Article;
import org.demo.blog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文章的controller
 * @author tomdog
 */
@RestController
public class ArticleController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private FileService fileService;

    /**
     * 查询文章列表（分页）
     * 键值对传参数：pageNum 当前页码，从1开始  pageSize 每页条数
     * @return
     */
    @GetMapping("/article/list")
    public HttpResult list(PageQuery pageQuery) {
        // 查询全部文章
        // List<Article> list = articleService.listAll();
        PageResult<Article> page = articleService.selectPage(pageQuery);
        return HttpResult.success(page);
    }

    /**
     * 查询文章列表
     * @return
     */
    @GetMapping("/article/listAll")
    public HttpResult listAll() {
        // 查询全部文章
        List<Article> list = articleService.listAll();
        return HttpResult.success(list);
    }

    /**
     * 发布文章
     * @return
     */
    @PostMapping("/article")
    @NeedPermission("ARTICLE_PUBLISH")
    public HttpResult publish(@RequestBody Article article) {
        articleService.publish(article);
        // 保存之后数据返回给前端
        return HttpResult.success(article);
    }

    /**
     * 给文章添加图片
     */
    @PostMapping("/article/img")
    public HttpResult img(MultipartFile file, Long articleId) {
        // 上传头像
        SysFile upload = fileService.upload(file, "文章大图");
        // 修改这条数据的图片
        articleService.updateImg(articleId, upload.getPath());
        return HttpResult.success();
    }
}
